package com.gitee.sop.sdk.open.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitee.sop.sdk.client.OpenClient;
import com.gitee.sop.sdk.common.RequestMethod;
import com.gitee.sop.sdk.open.param.CommonParam;
import com.gitee.sop.sdk.open.param.LoginParam;
import com.gitee.sop.sdk.open.param.MongoParam;
import com.gitee.sop.sdk.open.param.StatusParam;
import com.gitee.sop.sdk.open.result.R;
import com.gitee.sop.sdk.request.CommonRequest;
import com.gitee.sop.sdk.response.CommonResponse;
import com.gitee.sop.sdk.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 认证模块开放功能接口
 *
 * @author: Admin
 * @date: 2021/3/16
 * @description:
 * @copyright: 重庆万蓝兴科技有限公司
 */
@Api(tags = "认证模块接口（蓝星云开放平台）")
@RestController
public class AuthApiController {

    @Autowired
    private OpenClient openClient;

    @ApiOperation(value = "接口转发", notes = "接口转发")
    @PostMapping(value = "/lxyCloud/forward", produces = {"application/json;charset=utf8"})
    public Object forward(@RequestBody CommonParam commonParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = new HashMap<>();
        if (Objects.nonNull(commonParam.getParams())) {
            bizMap = commonParam.getParams().getInnerMap();
        }
        RequestMethod requestMethod = RequestMethod.POST;
        String method = commonParam.getRequestMethod();
        switch (method) {
            case "GET":
                requestMethod = RequestMethod.GET;
                break;
            case "POST":
                requestMethod = RequestMethod.POST;
                break;
            case "PUT":
                requestMethod = RequestMethod.PUT;
                break;
            case "DELETE":
                requestMethod = RequestMethod.DELETE;
                break;
            default:
                break;
        }
        return commonSend(commonParam.getMethod(), requestMethod, bizMap, servletRequest);
    }


    //    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sendType", value = "验证码下发类型：normal/sms/email", dataType = "string", paramType = "query", required = true),
            @ApiImplicitParam(name = "username", value = "验证码接收者（邮箱/手机号/用户账号）", dataType = "string", paramType = "query", required = true)})
    @PostMapping(value = "/lxyCloud/auth/code", produces = {"application/json;charset=utf8"})
    public Object code(HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = new HashMap<>();
        return commonSend("open.auth.code.send", RequestMethod.POST, bizMap, servletRequest);
    }


    //    @ApiOperation(value = "登录/注册", notes = "登录/注册")
    @PostMapping(value = "/lxyCloud/auth/authorize", produces = {"application/json;charset=utf8"})
    public Object authorize(@RequestBody LoginParam loginParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = ObjectUtil.toMap(loginParam);
        return commonSend("open.auth.token.authorize", RequestMethod.POST, bizMap, servletRequest);
    }


    //    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/lxyCloud/auth/login", produces = {"application/json;charset=utf8"})
    public Object login(@RequestBody LoginParam loginParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = ObjectUtil.toMap(loginParam);
        return commonSend("open.auth.token.login", RequestMethod.POST, bizMap, servletRequest);
    }

    //    @ApiOperation(value = "注册", notes = "注册")
    @PostMapping(value = "/lxyCloud/auth/register", produces = {"application/json;charset=utf8"})
    public Object register(@RequestBody LoginParam loginParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = ObjectUtil.toMap(loginParam);
        return commonSend("open.auth.token.register", RequestMethod.POST, bizMap, servletRequest);
    }

    //    @ApiOperation(value = "分页查询注册用户列表", notes = "分页查询注册用户列表")
    @PostMapping(value = "/lxyCloud/auth/user/search/page", produces = {"application/json;charset=utf8"})
    public Object searchPage(@RequestBody MongoParam mongoParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = ObjectUtil.toMap(mongoParam);
        return commonSend("open.auth.user.searchPage", RequestMethod.POST, bizMap, servletRequest);
    }

    //    @ApiOperation(value = "查询指定用户详细信息", notes = "查询指定用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userUuid", value = "用户uuid", dataType = "string", paramType = "query", required = true)
    })
    @GetMapping(value = "/lxyCloud/auth/user/search/detail", produces = {"application/json;charset=utf8"})
    public Object userDetail(HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = new HashMap<>();
        return commonSend("open.auth.user.detail", RequestMethod.GET, bizMap, servletRequest);
    }

    //    @ApiOperation(value = "修改指定用户状态", notes = "修改指定用户状态")
    @PutMapping(value = "/lxyCloud/auth/user/changeStatus", produces = {"application/json;charset=utf8"})
    public Object userStatusChange(@RequestBody StatusParam statusParam, HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = ObjectUtil.toMap(statusParam);
        return commonSend("open.auth.user.changeStatus", RequestMethod.PUT, bizMap, servletRequest);
    }

    //    @ApiOperation(value = "删除指定用户（注销）", notes = "删除指定用户（注销）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userUuid", value = "用户uuid", dataType = "string", paramType = "query", required = true)
    })
    @DeleteMapping(value = "/lxyCloud/auth/user/delete", produces = {"application/json;charset=utf8"})
    public Object userDelete(HttpServletRequest servletRequest) {
        Map<String, Object> bizMap = new HashMap<>();
        return commonSend("open.auth.user.delete", RequestMethod.DELETE, bizMap, servletRequest);
    }

    /**
     * 通用发送处理
     *
     * @param method         发送方法名
     * @param requestMethod  请求方式
     * @param bizMap         业务参数
     * @param servletRequest 请求
     * @return
     */
    private Object commonSend(String method, RequestMethod requestMethod, Map<String, Object> bizMap, HttpServletRequest servletRequest) {
        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        if (null != parameterMap && parameterMap.size() > 0) {
            parameterMap.forEach((k, v) -> {
                bizMap.put(k, v[0]);
            });
        }
        CommonRequest request = new CommonRequest(method);
        request.setBizModel(bizMap);
        request.setRequestMethod(requestMethod);
        String appAuthToken = getAppAuthToken(bizMap, servletRequest);
        CommonResponse response = openClient.execute(request, appAuthToken);
        if (response.isSuccess()) {
            // 返回结果，body对应的是alipay_story_find_response部分
            String body = response.getBody();
            JSONObject jsonObject = JSON.parseObject(body);
            return jsonObject;
        }
        String message = StringUtils.isNotBlank(response.getSubMsg()) ? response.getSubMsg() : response.getMsg();
        return R.fail(message);
    }

    /**
     * 获取用户请求token
     *
     * @param bizMap         参数集
     * @param servletRequest 请求
     * @return
     */
    private String getAppAuthToken(Map<String, Object> bizMap, HttpServletRequest servletRequest) {
        String appAuthToken = servletRequest.getHeader("LXY-APP-AUTH-TOKEN");
        if (StringUtils.isBlank(appAuthToken)) {
            appAuthToken = servletRequest.getParameter("LXY-APP-AUTH-TOKEN");
        }
        if (StringUtils.isBlank(appAuthToken)) {
            Object authToken = bizMap.get("LXY-APP-AUTH-TOKEN");
            if (Objects.nonNull(authToken)) {
                appAuthToken = authToken.toString();
            }
        }

        if (StringUtils.isBlank(appAuthToken)) {
            appAuthToken = null;
        }
        return appAuthToken;
    }

}
